package com.small.account.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.small.account.entity.AuMechanism;
import com.small.account.mapper.AuMechanismMapper;
import com.small.account.service.IAuMechanismService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 公司部门 服务实现类
 * </p>
 *
 * @author wangguochao
 * @since 2021-01-27
 */
@Service
public class AuMechanismServiceImpl extends ServiceImpl<AuMechanismMapper, AuMechanism> implements IAuMechanismService {

    @Override
    public List<AuMechanism> findTree() {
        LambdaQueryWrapper<AuMechanism> query = Wrappers.lambdaQuery();
        query.orderByAsc(AuMechanism::getSortNumber)
                .orderByDesc(AuMechanism::getSortTime);
        List<AuMechanism> list = this.list(query);
        return this.recursion(list, "system");
    }

    public List<AuMechanism> recursion(List<AuMechanism> list, String parentId) {
        List<AuMechanism> arr = new ArrayList<>();
        for (AuMechanism auMechanism : list) {
            if (parentId == null && auMechanism.getParentId() == null) {
                List<AuMechanism> r = recursion(list, auMechanism.getId());
                auMechanism.setChildren(r);
                arr.add(auMechanism);
            } else if (parentId != null && parentId.equals(auMechanism.getParentId())) {
                List<AuMechanism> r = recursion(list, auMechanism.getId());
                auMechanism.setChildren(r);
                arr.add(auMechanism);
            }
        }
        return arr;
    }
}
